package com.bjpowernode.other.reentrantlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 解决死锁
 */
public class Lock01 {

    private static Lock lock1 = new ReentrantLock();
    private static Lock lock2 = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            m1();
        });
        Thread t2 = new Thread(() -> {
            m2();
        });

        t1.start();
        t2.start();

        Thread.sleep(5000);

        /**
         * 上面给了足够的时间让线程执行，若程序执行到这里线程仍然存活，则说明线程死锁了
         */
        if (t1.isAlive()) {
            t1.interrupt();
        }
        if (t2.isAlive()) {
            t2.interrupt();
        }
    }

    public static void m1() {
        try {
            //获取锁
            lock1.lockInterruptibly();
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(100);
            lock2.lockInterruptibly();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock2.unlock();
            lock1.unlock();
        }
    }


    public static void m2() {
        try {
            //获取锁
            lock2.lockInterruptibly();
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(100);
            lock1.lockInterruptibly();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock1.unlock();
            lock2.unlock();
        }
    }
}
